<template>
  <div class="relative">
    <button 
      type="button" 
      @click="togglePicker" 
      class="text-gray-400 hover:text-gray-500 focus:outline-none emoji-picker-button"
      :aria-expanded="isOpen"
      aria-haspopup="true"
    >
      <span class="text-xl">😊</span>
    </button>

    <div 
      v-if="isOpen" 
      class="emoji-picker-container absolute bottom-full right-0 mb-2 z-50 bg-white shadow-lg rounded-md overflow-hidden"
      style="width: 320px; max-height: 350px;"
      @click.stop=""
    >
      <div class="emoji-categories flex border-b border-gray-200">
        <button 
          v-for="category in categories" 
          :key="category.id"
          @click="selectCategory(category.id)"
          class="flex-1 py-2 hover:bg-gray-100"
          :class="selectedCategory === category.id ? 'text-primary border-b-2 border-primary' : 'text-gray-500'"
        >
          <span class="text-xl">{{ category.emoji }}</span>
        </button>
      </div>

      <div class="emoji-grid p-2 max-h-60 overflow-y-auto grid grid-cols-7 gap-1">
        <button 
          v-for="emoji in filteredEmojis" 
          :key="emoji.id"
          @click="selectEmoji(emoji)"
          class="text-2xl p-1 hover:bg-gray-100 rounded"
        >
          {{ emoji.native }}
        </button>
      </div>

      <div class="px-2 py-1 border-t border-gray-200 flex">
        <label for="emoji-search" class="sr-only">搜索表情</label>
        <input 
          id="emoji-search"
          v-model="searchQuery" 
          type="text" 
          placeholder="搜索表情..." 
          class="text-sm form-input py-1 flex-1"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, defineEmits, watch, onUnmounted } from 'vue';

const emit = defineEmits(['select']);

// 状态
const isOpen = ref(false);
const searchQuery = ref('');
const selectedCategory = ref('smileys');
const emojis = ref([]);
const categories = ref([
  { id: 'smileys', emoji: '😊' },
  { id: 'people', emoji: '👨' },
  { id: 'animals', emoji: '🐶' },
  { id: 'food', emoji: '🍔' },
  { id: 'activities', emoji: '⚽' },
  { id: 'travel', emoji: '🚗' },
  { id: 'objects', emoji: '💡' },
  { id: 'symbols', emoji: '❤️' },
  { id: 'flags', emoji: '🏁' }
]);

// 常用表情列表
const commonEmojis = [
  { id: 'smile', native: '😊', category: 'smileys' },
  { id: 'laugh', native: '😂', category: 'smileys' },
  { id: 'wink', native: '😉', category: 'smileys' },
  { id: 'heart_eyes', native: '😍', category: 'smileys' },
  { id: 'kissing_heart', native: '😘', category: 'smileys' },
  { id: 'stuck_out_tongue_winking_eye', native: '😜', category: 'smileys' },
  { id: 'expressionless', native: '😑', category: 'smileys' },
  { id: 'unamused', native: '😒', category: 'smileys' },
  { id: 'sweat_smile', native: '😅', category: 'smileys' },
  { id: 'pensive', native: '😔', category: 'smileys' },
  { id: 'confused', native: '😕', category: 'smileys' },
  { id: 'confounded', native: '😖', category: 'smileys' },
  { id: 'crying', native: '😢', category: 'smileys' },
  { id: 'persevere', native: '😣', category: 'smileys' },
  { id: 'sleepy', native: '😪', category: 'smileys' },
  { id: 'astonished', native: '😲', category: 'smileys' },
  { id: 'mask', native: '😷', category: 'smileys' },
  { id: 'thumbsup', native: '👍', category: 'people' },
  { id: 'thumbsdown', native: '👎', category: 'people' },
  { id: 'ok_hand', native: '👌', category: 'people' },
  { id: 'punch', native: '👊', category: 'people' },
  { id: 'v', native: '✌️', category: 'people' },
  { id: 'wave', native: '👋', category: 'people' },
  { id: 'pray', native: '🙏', category: 'people' },
  { id: 'clap', native: '👏', category: 'people' },
  { id: 'heart', native: '❤️', category: 'symbols' },
  { id: 'broken_heart', native: '💔', category: 'symbols' },
  { id: 'sparkles', native: '✨', category: 'symbols' },
  { id: 'fire', native: '🔥', category: 'symbols' },
  { id: 'star2', native: '⭐', category: 'symbols' },
  { id: 'cake', native: '🍰', category: 'food' },
  { id: 'coffee', native: '☕', category: 'food' },
  { id: 'gift', native: '🎁', category: 'objects' },
  { id: 'bulb', native: '💡', category: 'objects' },
  { id: 'camera', native: '📷', category: 'objects' }
];

// 计算当前可用的表情
const filteredEmojis = computed(() => {
  if (searchQuery.value) {
    return commonEmojis.filter(emoji => 
      emoji.id.includes(searchQuery.value.toLowerCase())
    );
  } else {
    return commonEmojis.filter(emoji => 
      emoji.category === selectedCategory.value
    );
  }
});

// 监听搜索框输入，有内容时取消分类选择
watch(searchQuery, (newVal) => {
  if (newVal) {
    selectedCategory.value = '';
  } else {
    selectedCategory.value = 'smileys';
  }
});

// 点击外部关闭选择器
function setupClickOutside() {
  function handleClickOutside(event: MouseEvent) {
    const target = event.target as HTMLElement;
    const pickerContainer = document.querySelector('.emoji-picker-container');
    const pickerButton = target.closest('.emoji-picker-button');
    
    if (isOpen.value && pickerContainer && !pickerContainer.contains(target) && !pickerButton) {
      isOpen.value = false;
    }
  }
  
  // 在onMounted中添加事件监听，在onUnmounted中移除
  onMounted(() => {
    document.addEventListener('click', handleClickOutside);
  });
  
  // 清理事件
  onUnmounted(() => {
    document.removeEventListener('click', handleClickOutside);
  });
}

// 切换选择器显示状态
function togglePicker() {
  console.log('Toggling picker, current isOpen:', isOpen.value);
  isOpen.value = !isOpen.value;
  console.log('New isOpen value:', isOpen.value);
}

// 选择分类
function selectCategory(category: string) {
  selectedCategory.value = category;
  searchQuery.value = '';
}

// 选择表情
function selectEmoji(emoji: any) {
  emit('select', emoji.native);
  isOpen.value = false;
}

// 设置点击外部关闭
setupClickOutside();
</script>

<style scoped>
.emoji-grid::-webkit-scrollbar {
  width: 4px;
}

.emoji-grid::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.emoji-grid::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 4px;
}

.emoji-grid::-webkit-scrollbar-thumb:hover {
  background: #555;
}

.emoji-picker-container {
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
  border: 1px solid #e5e7eb;
}
</style> 